import { useMemo, useState } from "react";
import Navbar from "../../compoents/Navbar";
import { useNavigate } from "react-router-dom";
import style from "./index.module.css";
import request from "../../api/request";
import { useCountdown } from "../../utils/useCountdown";
import { useDebunce } from "../../utils/useDebunce";
import { Form, Input, Button, Toast, DatePicker, Picker } from "antd-mobile";

// API响应类型定义
interface ApiResponse {
  code: number;
  data: string | number | object | null;
  msg: string;
}

function Index() {
  const navigate = useNavigate();
  const { count, CountDown } = useCountdown();
  const [form] = Form.useForm();
  const [selectedRelationship, setSelectedRelationship] = useState("friend"); // 默认选择朋友
  const maxNum = 60;
  const [applicationType, setApplicationType] = useState("agent"); // 默认选择代理人办理
  const [admissionDate, setAdmissionDate] = useState(new Date("2020-01-03"));
  const [dischargeDate, setDischargeDate] = useState(new Date("2020-02-01"));
  const [showAdmissionPicker, setShowAdmissionPicker] = useState(false);
  const [showDischargePicker, setShowDischargePicker] = useState(false);
  const [showRelationshipPicker, setShowRelationshipPicker] = useState(false);
  const [uploadedImages, setUploadedImages] = useState({
    front: null as File | null,
    back: null as File | null,
    handheld: null as File | null,
  });
  const [uploadedPOAImages, setUploadedPOAImages] = useState({
    poa1: null as File | null,
    poa2: null as File | null,
    poa3: null as File | null,
  });
  const [relationshipOptions] = useState([
    { value: "spouse", label: "配偶" },
    { value: "parent", label: "父母" },
    { value: "child", label: "子女" },
    { value: "sibling", label: "兄弟姐妹" },
    { value: "other", label: "其他" },
  ]);

  // 格式化日期为 YYYY/MM/DD 格式
  const formatDate = (date: Date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}/${month}/${day}`;
  };

  // 处理图片上传
  const handleImageUpload = (type: "front" | "back" | "handheld") => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        setUploadedImages((prev) => ({
          ...prev,
          [type]: file,
        }));
        Toast.show({ content: "图片上传成功" });
      }
    };
    input.click();
  };

  // 处理代办人委托书照片上传
  const handlePOAImageUpload = (type: "poa1" | "poa2" | "poa3") => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        // 检查文件大小（最大10M）
        if (file.size > 10 * 1024 * 1024) {
          Toast.show({ content: "文件大小不能超过10M" });
          return;
        }
        // 检查文件格式
        const validTypes = ["image/jpeg", "image/jpg", "image/png"];
        if (!validTypes.includes(file.type)) {
          Toast.show({ content: "只支持JPG/PNG格式" });
          return;
        }
        setUploadedPOAImages((prev) => ({
          ...prev,
          [type]: file,
        }));
        Toast.show({ content: "委托书照片上传成功" });
      }
    };
    input.click();
  };

  const sendCode = useMemo(() => {
    if (count === maxNum) return "获取验证码";
    return `${count}秒后重新获取`;
  }, [count]);

  // 获取验证码处理函数
  const handBtn = useDebunce(() => {
    // 先获取手机号值，用于调试
    const phoneValue = form.getFieldValue("phone");
    console.log("当前手机号值:", phoneValue);

    form
      .validateFields(["phone"])
      .then(async ({ phone }) => {
        console.log("验证通过，手机号:", phone);
        CountDown();
        try {
          const res = (await request.post("/api/login", {
            phone: phone,
            code: "", // 获取验证码时不需要code
          })) as ApiResponse;

          if (res.code === 20000) {
            Toast.show({ content: "验证码已发送" });
            // 模拟验证码自动填入（实际项目中应该由用户手动输入）
            setTimeout(() => {
              form.setFieldValue("code", res.data);
            }, 2000);
          } else {
            Toast.show({ content: res.msg || "验证码发送失败" });
          }
        } catch (error) {
          Toast.show({ content: "验证码发送失败，请重试" });
          console.error("发送验证码失败:", error);
        }
      })
      .catch((error) => {
        console.log("表单验证失败详情:", error);
        console.log("手机号字段错误:", error.errorFields);
        Toast.show({ content: "请先输入正确的手机号" });
      });
  }, 1000);

  const onFinish = async () => {
    form
      .validateFields()
      .then(async (formValues) => {
        const res = (await request.post(
          "/api/login",
          formValues
        )) as ApiResponse;
        console.log(res);
        if (res.code === 20000) {
          Toast.show({ content: "提交成功" });
          // navigate('/index')
          setTimeout(() => {
            form.setFieldValue("code", res.data);
          }, 1000);
        } else {
          Toast.show({ content: res.msg });
        }
      })
      .catch((error) => {
        Toast.show({ content: "表单验证失败，请检查输入" });
        console.error("表单验证失败:", error);
      });
  };

  return (
    <div>
      <Navbar title="住院病案申请" showBack onBack={() => navigate(-1)} />

      <div className={style.content}>
        <div className={style.progressContainer}>
          <div className={style.progressSteps}>
            <div className={`${style.step} ${style.active}`}>
              <div className={style.stepCircle}>1</div>
              <div className={style.stepLabel}>基本信息</div>
            </div>
            <div className={style.stepLine}></div>
            <div className={style.step}>
              <div className={style.stepCircle}>2</div>
              <div className={style.stepLabel}>复印内容</div>
            </div>
            <div className={style.stepLine}></div>
            <div className={style.step}>
              <div className={style.stepCircle}>3</div>
              <div className={style.stepLabel}>邮寄方式</div>
            </div>
          </div>
        </div>

        <div>
          <Form
            form={form}
            name="form"
            onFinish={onFinish}
            footer={
              <Button block type="submit" color="primary" size="large">
                提交
              </Button>
            }
          >
            <Form.Header>请完善以下基本信息</Form.Header>

            <div className={style.applicationTypeContainer}>
              <div className={style.applicationTypeLabel}>申请类型</div>
              <div className={style.radioGroup}>
                <div
                  className={`${style.radioOption} ${
                    applicationType === "self" ? style.active : ""
                  }`}
                  onClick={() => setApplicationType("self")}
                >
                  <div className={style.radioCircle}>
                    {applicationType === "self" && (
                      <div className={style.radioDot}></div>
                    )}
                  </div>
                  <span className={style.radioLabel}>本人办理</span>
                </div>
                <div
                  className={`${style.radioOption} ${
                    applicationType === "agent" ? style.active : ""
                  }`}
                  onClick={() => setApplicationType("agent")}
                >
                  <div className={style.radioCircle}>
                    {applicationType === "agent" && (
                      <div className={style.radioDot}></div>
                    )}
                  </div>
                  <span className={style.radioLabel}>代理人办理</span>
                </div>
              </div>
            </div>

            <Form.Item
              name="name"
              label="姓名"
              rules={[{ required: true, message: "姓名不能为空" }]}
            >
              <Input onChange={console.log} placeholder="请输入姓名" />
            </Form.Item>

            <Form.Item
              name="namecode"
              label="身份证号"
              rules={[{ required: true, message: "身份证号不能为空" }]}
            >
              <Input onChange={console.log} placeholder="请输入身份证号" />
            </Form.Item>

            <Form.Item
              name="phone"
              label="本人电话"
              rules={[
                { required: true, message: "手机号不能为空" },
                { pattern: /^1\d{10}$/, message: "请输入正确的11位手机号" },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              label="验证码"
              extra={
                <Button
                  disabled={count !== maxNum}
                  onClick={() => handBtn()}
                  size="small"
                  color="primary"
                >
                  {sendCode}
                </Button>
              }
              rules={[{ required: true, message: "验证码不能为空" }]}
            >
              <Input placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item
              name="hospcode"
              label="住院号"
              rules={[{ required: true, message: "住院号不能为空" }]}
            >
              <Input onChange={console.log} placeholder="请输入住院号" />
            </Form.Item>

            <div className={style.dateSection}>
              <div className={style.dateField}>
                <label className={style.dateLabel}>入院时间*</label>
                <div className={style.dateInputContainer}>
                  <input
                    type="text"
                    value={formatDate(admissionDate)}
                    className={style.dateInput}
                    readOnly
                  />
                  <div
                    className={style.calendarIcon}
                    onClick={() => setShowAdmissionPicker(true)}
                  >
                    📅
                  </div>
                </div>
              </div>

              <div className={style.dateField}>
                <label className={style.dateLabel}>出院时间*</label>
                <div className={style.dateInputContainer}>
                  <input
                    type="text"
                    value={formatDate(dischargeDate)}
                    className={style.dateInput}
                    readOnly
                  />
                  <div
                    className={style.calendarIcon}
                    onClick={() => setShowDischargePicker(true)}
                  >
                    📅
                  </div>
                </div>
              </div>
            </div>

            <DatePicker
              visible={showAdmissionPicker}
              onClose={() => setShowAdmissionPicker(false)}
              onConfirm={(val) => {
                setAdmissionDate(val);
                setShowAdmissionPicker(false);
              }}
              value={admissionDate}
              title="选择入院时间"
            />

            <DatePicker
              visible={showDischargePicker}
              onClose={() => setShowDischargePicker(false)}
              onConfirm={(val) => {
                setDischargeDate(val);
                setShowDischargePicker(false);
              }}
              value={dischargeDate}
              title="选择出院时间"
            />

            <Picker
              visible={showRelationshipPicker}
              onClose={() => setShowRelationshipPicker(false)}
              onConfirm={(val) => {
                form.setFieldValue("relationship", val[0]);
                setShowRelationshipPicker(false);
              }}
              columns={[relationshipOptions]}
              title="选择关系"
            />

            {/* 身份证照片上传区域 */}
            <div className={style.idCardSection}>
              <div className={style.idCardLabel}>代办人身份证照片*</div>

              <div className={style.uploadGrid}>


                <div className={style.uploadItem}>
                  <div
                    className={style.uploadBox}
                    onClick={() => handleImageUpload("front")}
                  >
                    {uploadedImages.front ? (
                      <div className={style.uploadedImage}>
                        <img
                          src={URL.createObjectURL(uploadedImages.front)}
                          alt="正面身份证"
                        />
                        <div className={style.uploadSuccess}>✓</div>
                      </div>
                    ) : (
                      <>
                        <div className={style.plusIcon}>+</div>
                        <div className={style.uploadText}>正面身份证</div>
                      </>
                    )}
                  </div>
                </div>

                <div className={style.uploadItem}>
                  <div
                    className={style.uploadBox}
                    onClick={() => handleImageUpload("back")}
                  >
                    {uploadedImages.back ? (
                      <div className={style.uploadedImage}>
                        <img
                          src={URL.createObjectURL(uploadedImages.back)}
                          alt="反面身份证"
                        />
                        <div className={style.uploadSuccess}>✓</div>
                      </div>
                    ) : (
                      <>
                        <div className={style.plusIcon}>+</div>
                        <div className={style.uploadText}>反面身份证</div>
                      </>
                    )}
                  </div>
                </div>

                <div className={style.uploadItem}>
                  <div
                    className={style.uploadBox}
                    onClick={() => handleImageUpload("handheld")}
                  >
                    {uploadedImages.handheld ? (
                      <div className={style.uploadedImage}>
                        <img
                          src={URL.createObjectURL(uploadedImages.handheld)}
                          alt="手持身份证"
                        />
                        <div className={style.uploadSuccess}>✓</div>
                      </div>
                    ) : (
                      <>
                        <div className={style.plusIcon}>+</div>
                        <div className={style.uploadText}>手持身份证</div>
                      </>
                    )}
                  </div>
                </div>

                
              </div>
            </div>

          
            {/* 代办人基本信息 */}
            <div className={style.agentInfoSection}>
              <div className={style.agentInfoLabel}>
                请完善以下代办人基本信息
              </div>

              <div className={style.relationshipField}>
                <Form.Item
                  name="relationship"
                  label="关系"
                  className={style.relationshipField}
                ></Form.Item>

                <div>
                  <select 
                    id="mySelect" 
                    value={selectedRelationship}
                    onChange={(e) => {
                      setSelectedRelationship(e.target.value);
                      form.setFieldValue("relationship", e.target.value);
                    }}
                  >
                    <option value="">请选择代办人与患者关系</option>
                    <option value="spouse">配偶</option>
                    <option value="parent">父母</option>
                    <option value="child">子女</option>
                  </select>
                </div>

                
              </div>

              <Form.Item
                name="agentName"
                label="代办人姓名*"
                rules={[{ required: true, message: "代办人姓名不能为空" }]}
              >
                <Input placeholder="请输入代办人姓名" />
              </Form.Item>

              <Form.Item
                name="agentIdCard"
                label="代办人身份证号*"
                rules={[{ required: true, message: "代办人身份证号不能为空" }]}
              >
                <Input placeholder="请输入代办人身份证号" />
              </Form.Item>

              <Form.Item
                name="agentPhone"
                label="代办人电话*"
                rules={[
                  { required: true, message: "代办人电话不能为空" },
                  { pattern: /^1\d{10}$/, message: "请输入正确的11位手机号" },
                ]}
              >
                <Input placeholder="请输入代办人联系电话" />
              </Form.Item>
            </div>

            {/* 代办人委托书照片上传区域 */}
            <div className={style.poaSection}>
              <div className={style.poaLabel}>
                代办人委托书照片*
                
              </div>
              <div className={style.uploadGrid}>
                <div className={style.uploadItem}>
                  <div className={style.uploadBox} onClick={() => handlePOAImageUpload('poa1')}>
                    {uploadedPOAImages.poa1 ? (
                      <div className={style.uploadedImage}>
                        <img src={URL.createObjectURL(uploadedPOAImages.poa1)} alt="代办人委托书1" />
                        <div className={style.uploadSuccess}>✓</div>
                      </div>
                    ) : (
                      <>
                        <div className={style.plusIcon}>+</div>
                        <div className={style.uploadText}>代办人委托书1</div>
                      </>
                    )}
                  </div>
                </div>
                <div className={style.uploadItem}>
                  <div className={style.uploadBox} onClick={() => handlePOAImageUpload('poa2')}>
                    {uploadedPOAImages.poa2 ? (
                      <div className={style.uploadedImage}>
                        <img src={URL.createObjectURL(uploadedPOAImages.poa2)} alt="代办人委托书2" />
                        <div className={style.uploadSuccess}>✓</div>
                      </div>
                    ) : (
                      <>
                        <div className={style.plusIcon}>+</div>
                        <div className={style.uploadText}>代办人委托书2</div>
                      </>
                    )}
                  </div>
                </div>
                <div className={style.uploadItem}>
                  <div className={style.uploadBox} onClick={() => handlePOAImageUpload('poa3')}>
                    {uploadedPOAImages.poa3 ? (
                      <div className={style.uploadedImage}>
                        <img src={URL.createObjectURL(uploadedPOAImages.poa3)} alt="代办人委托书3" />
                        <div className={style.uploadSuccess}>✓</div>
                      </div>
                    ) : (
                      <>
                        <div className={style.plusIcon}>+</div>
                        <div className={style.uploadText}>代办人委托书3</div>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </div>

                      {/* 代办人委托书照片上传区域 */}
            <div className={style.poaSingleSection}>
              <div className={style.poaSingleLabel}>
                代办人委托书照片*
                <span className={style.viewExample}>查看示例</span>
              </div>
              <div className={style.singleUploadBox} onClick={() => handlePOAImageUpload('poa1')}>
                {uploadedPOAImages.poa1 ? (
                  <div className={style.uploadedImage}>
                    <img src={URL.createObjectURL(uploadedPOAImages.poa1)} alt="代办人委托书" />
                    <div className={style.uploadSuccess}>✓</div>
                  </div>
                ) : (
                  <>
                    <div className={style.plusIcon}>+</div>
                    <div className={style.uploadText}>代办人委托书</div>
                  </>
                )}
              </div>
              <div className={style.uploadInstructions}>
                <div className={style.instructionItem}>
                  1. 上传身份证图片支持JPG/PNG格式,最大支持10M
                </div>
                <div className={style.instructionItem}>
                  2. 如自拍摄照片则需保证照片清晰且填写真实有效,否则将降低申请通过率,请按要求拍摄,感谢您的支持
                </div>
              </div>
            </div>

            
          </Form>
        </div>
      </div>
    </div>
  );
}

export default Index;
